<script setup lang="ts">
import {ref, reactive, watch} from "vue";
import {getDishesList} from "@/api/dishes";
import {getIngredientsByType} from "@/api/ingredients";
import type {Page} from "@/api/page/types";
import type {Dishes, DishesSearchParam} from "@/api/dishes/type";
import type {Ingredients} from "@/api/ingredients/types";
import EtoakPager from "@/views/compoment/EtoakPager.vue";

const base_url = import.meta.env.VITE_APP_BASE_API

const queryForm = reactive<DishesSearchParam>({
  pageNum: 1,
  pageSize: 5,
  main: '',
  minor: '',
  seasoning: ''
})
const queryFormRef = ref()

const total = ref(0)
const dishesList = ref<Dishes[]>([])

const listDishes = () => {
  getDishesList(queryForm).then((resp: Page<Dishes>) => {
    total.value = resp.total
    dishesList.value = resp.rows
  }).catch(e => {
    console.log(e)
  })
}

const mainList = ref<Ingredients[]>([])
const minorList = ref<Ingredients[]>([])
const seasoningList = ref<Ingredients[]>([])

const getIngredientsList = async () => {
  try {
    mainList.value = await getIngredientsByType('1')
    minorList.value = await getIngredientsByType('2')
    seasoningList.value = await getIngredientsByType('3')
  } catch (e) {
    console.log(e)
  }
}

const search = () => {
  queryForm.pageNum = 1
  listDishes()
}

const resetQueryForm = () => {
  queryFormRef.value.resetFields()
  search()
}

/* 购物车相关功能 */
import type {Cart} from "@/api/cart/types";
import {getCartList, clearCart, deleteCart, saveOrUpdate} from "@/api/cart";
import {ElMessage} from "element-plus";

const cartList = ref<Cart[]>([])
const listCart = () => {
  getCartList().then((resp: Cart[]) => {
    cartList.value = resp
  }).catch(e => {
    console.log(e)
  })
}

const numChange = (cart: Cart) => {
  saveOrUpdate(cart).then(resp => {
    ElMessage.success('修改成功!')
  }).catch(e => {
    console.log(e)
  })
}

const deleteDishes = (id: number) => {
  deleteCart(id).then(resp => {
    cartList.value = cartList.value
        .filter(item => item.dishesId != id)
    ElMessage.success('操作成功!')
  }).catch(e => {
    console.log(e)
  })
}

const addToCart = (dishes: Dishes) => {
  let cart = (cartList.value.find(cart => cart.dishesId == dishes.id))
  if (cart) {
    cart.count++
  } else {
    cart = {dishesId: dishes.id as number, dishesName: dishes.name, count: 1}
  }

  // 添加或修改
  saveOrUpdate(cart).then(resp => {
    if (cart.count == 1) {
      cartList.value.push(cart)
    }
    ElMessage.success('修改成功!')
  }).catch(e => {
    console.log(e)
  })
}


/* 组件渲染后加载 */
getIngredientsList()
listDishes()
listCart()
</script>

<template>
  <div class="app-containers">
    <el-table
        border
        stripe
        :data="cartList"
        style="width: 100%;">
      <el-table-column label="菜品ID" prop="dishesId" align="center"/>
      <el-table-column label="菜品名称" prop="dishesName" align="center"/>
      <el-table-column label="菜品数量" align="center">
        <template #default="scope">
          <el-input-number :min="1" :max="10" v-model="scope.row.count" @change="numChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="删除" align="center">
        <template #default="scope">
          <el-button type="danger" plain icon="Delete" circle @click="deleteDishes(scope.row.dishesId)"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查询表单 -->
    <el-form
        ref="queryFormRef"
        :model="queryForm"
        inline>
      <!-- 主要食材 -->
      <el-form-item prop="main">
        <el-select
            v-model="queryForm.main"
            clearable
            style="width: 180px"
            placeholder="请选择主要食材">
          <el-option
              v-for="item in mainList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
        </el-select>
      </el-form-item>
      <!-- 辅助食材 -->
      <el-form-item prop="minor">
        <el-select
            v-model="queryForm.minor"
            clearable
            style="width: 180px"
            placeholder="请选择辅助食材">
          <el-option
              v-for="item in minorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
        </el-select>
      </el-form-item>
      <!-- 配料 -->
      <el-form-item prop="seasoning">
        <el-select
            v-model="queryForm.seasoning"
            clearable
            style="width: 180px"
            placeholder="请选择配料">
          <el-option
              v-for="item in seasoningList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="Search" @click="search">搜索</el-button>
        <el-button type="info" plain icon="Refresh" @click="resetQueryForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格展示 -->
    <el-row :gutter="10">
      <el-col
          :span="6"
          v-for="item in dishesList"
          :key="item.id">
        <el-card :body-style="{ padding: '0px' }" style="margin-bottom: 10px">
          <el-image
              :src="base_url + item.url"
              class="image"
              :preview-src-list="[base_url + item.url]"
              preview-teleported
          />
          <div style="padding: 14px;">
            <div class="dishes">
              <span>{{ item.name }}</span>
              <el-button type="primary" text @click="addToCart(item)">加入预制订单</el-button>
            </div>
            <div class="ingredients">
              <span>{{ item.mainName }}</span>
            </div>
            <div class="ingredients">
              <span>{{ item.minorName }}</span>
            </div>
            <div class="ingredients">
              <span>{{ item.seasoningName }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <etoak-pager
        :page-sizes="[5, 10, 20]"
        :total="total"
        v-model:page-num="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        @get-data="listDishes"/>
  </div>
</template>

<style scoped>
.image {
  width: 100%;
  display: block;
  height: 270px;
}

.dishes {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #1B1B1B;
  line-height: 1.4;
  height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  font-weight: bold;
  white-space: nowrap;
}

.ingredients {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}
</style>